﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace LCSFlashCards
{
    public class BoxSerializer<T>
    {
        public void SaveInFile(string filepath, Box<T> boxToSave)
        {
            Stream stream = File.Open(filepath, FileMode.Create);
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(stream, boxToSave);
            stream.Close();
        }
        public Box<T> LoadFromFile(string filename)
        {
            Box<T> boxToLoad;
            Stream stream = File.Open(filename, FileMode.Open);
            BinaryFormatter bFormatter = new BinaryFormatter();
            boxToLoad = (Box<T>)bFormatter.Deserialize(stream);
            stream.Close();
            return boxToLoad;
        }
        public Box<T> LoadFromByteArray(byte[] array)
        {
            Box<T> boxToLoad;
            MemoryStream stream = new MemoryStream(array);
            BinaryFormatter bFormatter = new BinaryFormatter();
            boxToLoad = (Box<T>)bFormatter.Deserialize(stream);
            stream.Close();
            return boxToLoad;
        }
        public byte[] SaveInByteArray(Box<T> boxToSave)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(stream, boxToSave);
            return stream.ToArray();
        }
    }
}
